package com.leador.core;

import com.leador.assist.DataQueueManager;
import com.leador.batch.BatchReportManager;
import com.leador.broadcase.StopServiceThread;
import com.leador.db.DBManger;
import com.leador.location.LocateHelper;
import com.leador.module.AppInfo;
import com.leador.service.LBSTraceService;
import com.leador.socket.SocketConnect;
import com.leador.socket.SocketMananger;
import com.leador.utils.TraceSeleGenre;
import com.leador.utils.Utils;

/**
 * Created by liuha on 2016/9/12.
 */
public class KernelRunnable implements  Runnable{
    private KernelThread kernelThread;
    private LocateHelper locateHelper;
    private DBManger dbManger;
    public KernelRunnable(KernelThread kernelThread,LocateHelper locateHelper){
        this.kernelThread = kernelThread;
        this.locateHelper = locateHelper;
    }
    @Override
    public void run() {
        boolean isCache = kernelThread.isCache;
        boolean isLogin = kernelThread.isLogin;
        int gatherInterval = kernelThread.gatherInterval;

        if(isCache || isLogin){ //缓存或者登陆都可以进来
            kernelThread.setPackCount();

            //socket
            if(isLogin && (TraceSeleGenre.NOT_DATA_SOCKET_CONNECT.getValue() == Trace.traceType|| TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType) ){
                kernelThread.reStartService(); //判断返回的时间跟发送时间等信息(暂时未使用)
            }

            if(locateHelper != null && gatherInterval * kernelThread.getPackCount() >= locateHelper.getGatherInterval()){
                kernelThread.clearPackCount();
                locateHelper.startLocation(kernelThread.getContext());
            }
        }

        if(TraceSeleGenre.DATA_HHTP.getValue() == Trace.traceType && isLogin){
            BatchReportManager.getInstance(kernelThread.getLbsTraceService(),kernelThread).batch();
            kernelThread.getHandler().postDelayed(this, locateHelper.getGatherInterval());
        }

        if(TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType){
            int queSize = 0;
            if(isCache){
                int time = 6000;
                kernelThread.setCacheCount();
                queSize = kernelThread.getQueSize();
                if(time == kernelThread.getCacheCount() * locateHelper.getGatherInterval() ||
                        queSize >= time / locateHelper.getGatherInterval()){
                    kernelThread.clearCacheCount();
                    insertDB();
                }
                kernelThread.getHandler().postDelayed(this,locateHelper.getGatherInterval());
            }else{
                if(!isLogin){//未登录
                    boolean isLogout = kernelThread.isLogout;
                    if(TraceSeleGenre.DATA_SOCKET.getValue() == Trace.traceType){
                        if(isLogout){
                            this.stopSocket();
                            return;
                        }
                    }else if(TraceSeleGenre.NOT_SOCKET_CONNECT.getValue() == Trace.traceType){
                        if(isLogout){
                            DataQueueManager.getInstance().clearData();
                            this.stopSocket();
                            return;
                        }
                        SocketConnect socketConnect = kernelThread.getSocketMananger().socketConnect;
                        if(socketConnect.socketIsConnect()){
                            //TODO sendSocketData
                            kernelThread.getSocketMananger().sendHeartData();
                            kernelThread.getHandler().postDelayed(this, locateHelper.getGatherInterval());
                        }
                    }
                    return;
                }
                int socketCount = kernelThread.getSocketCount();
                int heartCount = kernelThread.getHeartCount();
                queSize = kernelThread.getQueSize();
                kernelThread.clearCacheCount();
                kernelThread.setSocketCount();
                kernelThread.setHeartCount();
                DataQueueManager.getInstance().UpLoadToTempBuffer();
                //个数大于要发送的包
                if(queSize >= kernelThread.packIntervalTime / locateHelper.getGatherInterval()){
                    //发送
                    boolean sendResult = kernelThread.getSocketMananger().sendData();
                    if(!sendResult){
                        kernelThread.getSocketMananger().sendHeartData();
                    }

                    if(heartCount * kernelThread.gatherInterval >= AppInfo.heartbeat_period*1000){
                        kernelThread.getSocketMananger().sendHeartData();
                    }

                    kernelThread.clearHeartCount();
                    kernelThread.clearSocketCount();
                //大于 发送包
                }else if(socketCount*kernelThread.gatherInterval >= kernelThread.packIntervalTime){
                    kernelThread.clearHeartCount();
                    kernelThread.clearSocketCount();
                    if(queSize > 0){
                        boolean sendResult = kernelThread.getSocketMananger().sendData();
                        if(!sendResult){
                            kernelThread.getSocketMananger().sendHeartData();
                        }
                    }else{
                        kernelThread.getSocketMananger().sendHeartData();
                    }
                // 大于 心跳包
                }else if(heartCount*kernelThread.gatherInterval>=AppInfo.heartbeat_period*1000){
                        kernelThread.clearHeartCount();
                        kernelThread.getSocketMananger().sendHeartData();
                }
                //继续循环
                kernelThread.getHandler().postDelayed(this, locateHelper.getGatherInterval());
            }
        }
    }

    /**
     * 缓存入口 并且标注 数据库有数据
     */
    public void insertDB(){
        LBSTraceService lbsTraceService = kernelThread.getLbsTraceService();
        dbManger = new DBManger(lbsTraceService);
        dbManger.insert();
        DataQueueManager.getInstance().setDbHasValue(true);
    }

    public void stopSocket(){
        if(kernelThread.getQueSize() > 0){
            SocketMananger socketMananger = kernelThread.getSocketMananger();
            if(socketMananger == null){
              return;
            }
            boolean hasNet = Utils.isNetworkConnected(kernelThread.getContext());
            boolean haSocketConnect = socketMananger.socketConnect.socketIsConnect();
            if(haSocketConnect&&hasNet){
                if(!kernelThread.getSocketMananger().sendData()){
                    kernelThread.getSocketMananger().sendHeartData();
                }
                kernelThread.getHandler().postDelayed(this, 1000L);
                return;
            }

            insertDB();
            if(kernelThread.getHandler() != null){
                kernelThread.getHandler().obtainMessage(141).sendToTarget();
                return;
            }
        }else{
            kernelThread.stopServiceFlag = Utils.getSystemTime();
            new StopServiceThread(kernelThread).start();
        }
    }
}
